# coding:utf-8
import time, re, os
import uiautomator2 as u2
import imagehash
import logging
from dao import SQLiteDb
from PIL import Image, ImageFile

#连接到MUMU模拟器
d    = u2.connect('127.0.0.1:7555')
dao  = SQLiteDb('./%s.db' % time.strftime('%Y%m%d', time.localtime(time.time())))
tmp  = ''
#底部计数
repeat = 0
#正计数
cnum   = 0

logger = logging.getLogger(__name__)
def initloger():
    if not os.path.exists('./logs'):
        os.mkdir('./logs')
    logger.setLevel(logging.DEBUG)
    fh = logging.FileHandler('./logs/%s.log' % time.strftime('%Y%m%d', time.localtime(time.time())), encoding='utf-8', mode='a')
    formatter = logging.Formatter("%(asctime)s - %(message)s", datefmt='%Y-%m-%d %H:%M:%S')
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    sh = logging.StreamHandler()
    sh.setFormatter(formatter)
    logger.addHandler(sh)
initloger()

def start():
    #d.app_start('com.st.QSB')
    logger.info('启动APP')
    d(text="往约").click()
    while True:
        if d.xpath('//*[@resource-id="com.st.QSB:id/common_tab"]/android.widget.LinearLayout[1]/android.widget.RelativeLayout[2]').exists:
            d.xpath('//*[@resource-id="com.st.QSB:id/common_tab"]/android.widget.LinearLayout[1]/android.widget.RelativeLayout[2]').click()
            break
        else:
            time.sleep(1)
    time.sleep(3)

def locity():
    logger.info('载入城市列表')
    city_  = ''
    citys  = {}
    try:
        d(resourceId="com.st.QSB:id/ctv_bgatitlebar_left").click()
        time.sleep(1)
        d(resourceId="com.st.QSB:id/selectCityTv").click()
        time.sleep(1)
        while True:
            linear = d(resourceId="com.st.QSB:id/cityNameTv")
            if city_ != linear[len(linear)-1].get_text():
                city_ = linear[len(linear)-1].get_text()
            else:
                break
            
            for i in range(0, len(linear)):
                city = linear[i].get_text()
                citys[city] = 1
            
            time.sleep(1)
            d.swipe(390, 1120, 496, 385, 0.5)
            time.sleep(1)
        time.sleep(1)
        d(resourceId="com.st.QSB:id/closeIv").click()
        time.sleep(1)
        d(resourceId="com.st.QSB:id/ctv_bgatitlebar_left").click()
    except:
        pass
    return citys

def selcity(city):
    logger.info('选择城市 - %s' % city)
    time.sleep(1)
    d(resourceId="com.st.QSB:id/ctv_bgatitlebar_left").click()
    time.sleep(3)
    d(resourceId="com.st.QSB:id/selectCityTv").click()
    time.sleep(3)
    d(resourceId="com.st.QSB:id/searchEt").click()
    d.set_fastinput_ime(True)
    d.send_keys(city)
    d.set_fastinput_ime(False)
    time.sleep(2)
    d.xpath('//*[@resource-id="com.st.QSB:id/searchRv"]/android.widget.LinearLayout[1]/android.widget.TextView[1]').click()
    time.sleep(2)
    d(resourceId="com.st.QSB:id/searchEt").click()
    d.set_fastinput_ime(True)
    d.send_keys("中")
    d.set_fastinput_ime(False)
    time.sleep(2)
    d.xpath('//*[@resource-id="com.st.QSB:id/searchRv"]/android.widget.LinearLayout[1]').child('android.widget.LinearLayout').click()
    #等待重加载
    time.sleep(5)

def swipe(city = '', index = 1):
    global tmp, repeat, cnum
    try:
        if d(resourceId="com.st.QSB:id/dataTv").exists:
            #无数据
            return False
        wds = d.xpath('//*[@resource-id="com.st.QSB:id/recyclerView"]/android.widget.FrameLayout').all()
        if index == 2 and len(wds) == 1:
            #只有一条数据
            return False
        div = d.xpath('//*[@resource-id="com.st.QSB:id/recyclerView"]/android.widget.FrameLayout['+ str(index) +']/android.widget.RelativeLayout[1]/android.view.ViewGroup[1]')
        #从一个视窗一个布局取
        lis = div.child('android.widget.TextView').all()
        nickName = lis[0].text
        sevicecount = lis[len(lis)-1].text
        if sevicecount.startswith('已接'):
            sevicecount = str(re.sub("\D", "", sevicecount))
        else:
            sevicecount = '0'

        agentIv = d(resourceId='com.st.QSB:id/agentIv')
        agentInfo = agentIv[0].info
        if index == 3:
            agentInfo = agentIv[1].info
        left  = agentInfo['bounds']['left']
        top   = agentInfo['bounds']['top']

        image = d.screenshot()
        image_path = './screen.jpg'
        agent_path = './%s.png' % nickName
        image.save(image_path)
        oldpic = Image.open(image_path)
        newpic = oldpic.crop((left, top, left+65, top+35))
        newpic.save(agent_path)
        time.sleep(0.5)
        if compare_image_with_hash(agent_path, './agent.png'):
            agent = '直营'
        else:
            agent = '代理'

        tm = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        if tmp != nickName:
            cnum += 1
            logger.info(cnum, city, nickName, sevicecount, '-', agent, str(tm))
            dao.addUsers(city, nickName, sevicecount, '-', agent, str(tm))
            tmp = nickName

        #记录页面底部
        page_content = d.dump_hierarchy()[(len(d.dump_hierarchy()) // 2):]
            
        if index == 2:
            d.swipe(390, 1020, 496, 585, 0.5)
        time.sleep(0.5)

        new_page_content = d.dump_hierarchy()[(len(d.dump_hierarchy()) // 2):]
        #页面底部重复则计次
        if new_page_content == page_content:
                repeat += 1

        os.remove(image_path)
        os.remove(agent_path)

    except Exception as e:
        logger.info('::ERROR::' + str(e))
        time.sleep(1)
    return True

def compare_image_with_hash(image_one, image_two, max_diff=1):
    ImageFile.LOAD_TRUNCATED_IMAGES = True
    hash_1 = imagehash.average_hash(Image.open(image_one))
    hash_2 = imagehash.average_hash(Image.open(image_two))
    diff = hash_1 - hash_2
    if diff < 0:
        diff = -diff
    if diff <= max_diff:
        return True
    else:
        return False

def main():
    global repeat, cnum
    start()
    citys = locity()
    for city in citys:
        selcity(city)
        cnum = 0
        swipe(city)
        while True:
            has = swipe(city, 2)
            if not has:
                break
            #重复5次说明到底了
            if repeat == 5:
                repeat = 0
                swipe(city, 3)
                break
    logger.info('采集完成 - 正在关机')
    os.system('shutdown /s /t 5')

if __name__ == '__main__':
    main()